//
//  GSComomRegisterSMSVerifyController.m
//  GSLoginDemo
//
//  Created by guoshikeji_a on 2018/7/27.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "GSComomRegisterSMSVerifyController.h"

#import "GSCommonLoginVerificationCodeView.h"

#import "GSCommonLoginVerificationCodeButton.h"

#import "GSCommonLoginPointAlertLabelView.h"

#import "GSCommonLoginSuccessController.h"

#import "NSString+GSCommonLogin.h"
//
#import "NSString+RegexCategory.h"


//request
#import "BCPhoneCaptchaRequest.h"//请求发送手机验证码
#import "BCEmailCaptchaRequest.h"//请求发送邮箱验证码
#import "BCPhoneRegisterRequest.h"//手机号码验证注册请求
#import "BCEmailRegisterRequest.h"//邮箱验证注册请求


@interface GSComomRegisterSMSVerifyController ()

@property (nonatomic, strong) GSCommonLoginVerificationCodeView *verifyCodeView;

/**
 *GSCommonLoginVerificationCodeButton
 */
@property (nonatomic, strong) GSCommonLoginVerificationCodeButton *codeButton;

@end

@implementation GSComomRegisterSMSVerifyController

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.largeTitleLabel.text = GSLoginLocalized(@"Enter Verification Code");
    NSString *account = [GSCommonLoginDataManager sharedData].registerModel.username;
    //
    NSString *subStr;
    //
    GSCCommonLoginAccountType type = [NSString gscLoginAccountTypeWithString:account];
    if (type==GSCCommonLoginAccountTypePhone) {
        account = [NSString phoneNumberPrivacyFrom:account];
        subStr = GSLoginLocalizedFormatString(@"We have send captcha to Phone-%@,Please pay attention to check",account);
    }else {
        subStr = GSLoginLocalizedFormatString(@"We have send captcha to Email-%@,Please pay attention to check",account);
    }
    //
    NSMutableAttributedString *attriText = [[NSMutableAttributedString alloc] initWithString:subStr];
    NSRange range = [subStr rangeOfString:account];
    if (range.location!=NSNotFound) {
        [attriText addAttributes:@{NSForegroundColorAttributeName:GSLOGIN_THEME_COLOR} range:range];
    }
    self.subTitleLabel.attributedText = attriText;
    [self setupSubviews];
    //
    //
    __weak typeof(self) wself = self;
    self.verifyCodeView.verifyCodeComplete = ^(BOOL compelte) {
        if (wself.nextStepButton.enabled!=compelte) {
            wself.nextStepButton.enabled = compelte;
        }
    };
    //
    self.codeButton.verifyCodeStatus = GSCommonLoginVerificationCodeStatusWaiting;
    
    //唤起输入
    [self.verifyCodeView beginInputAction];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setupSubviews {
    self.verifyCodeView = [GSCommonLoginVerificationCodeView new];
    self.verifyCodeView.verifyCodeDigits = 6;
    [self.view addSubview:self.verifyCodeView];
    //
    CGSize size = [GSCommonLoginVerificationCodeView viewSizeWithVerifyCodeDigits:self.verifyCodeView.verifyCodeDigits];
    [self.verifyCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.subTitleLabel.mas_bottom).offset(30.0);
        make.left.mas_equalTo(self.view).offset(21.0);
        make.size.mas_equalTo(size);
    }];
    //
    self.codeButton = [GSCommonLoginVerificationCodeButton new];
    [self.view addSubview:self.codeButton];
    [self.codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.verifyCodeView.mas_bottom).offset(16.0);
        make.left.mas_equalTo(self.verifyCodeView);
    }];
    [self.codeButton addTarget:self action:@selector(codeButtonDidClickedAction:) forControlEvents:UIControlEventTouchUpInside];
    //
    [self.view addSubview:self.nextStepButton];
    [self.nextStepButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.codeButton.mas_bottom).offset(55.0);
        make.centerX.mas_equalTo(self.view);
        make.size.mas_equalTo([GSCommonLoginButton defaultSize]);
    }];
    CGFloat leftPadding = 20.0;
    CGFloat rightPadding = 12.5;
    GSCommonLoginPointAlertLabelView* lableView = [GSCommonLoginPointAlertLabelView new];
    [self.view addSubview:lableView];
    [lableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.nextStepButton.mas_bottom).offset(25.0);
        make.left.mas_equalTo(leftPadding);
        make.width.mas_equalTo(self.view.frame.size.width-leftPadding-rightPadding);
    }];
    NSString *account = [GSCommonLoginDataManager sharedData].registerModel.username;
    GSCCommonLoginAccountType type = [NSString gscLoginAccountTypeWithString:account];
    if (type==GSCCommonLoginAccountTypePhone) {
        lableView.alertString = GSLoginLocalized(@"To bind the mobile phone number, and improve the safety");
    }else {
        lableView.alertString = GSLoginLocalized(@"To bind the email, and improve the safety");
    }
    //
    [self.view layoutIfNeeded];
}

#pragma mark - 发送验证码
- (void)codeButtonDidClickedAction:(QMUIButton *)button {
    [self.view endEditing:true];
    NSString *account = [GSCommonLoginDataManager sharedData].registerModel.username;
    GSCCommonLoginAccountType type = [NSString gscLoginAccountTypeWithString:account];
    if (type==GSCCommonLoginAccountTypePhone) {
        [self requestPhoneCaptcha:account];
    }else {
        [self requestEmailCaptchaAddress:account];
    }
}
//发送手机验证码
- (void)requestPhoneCaptcha:(NSString *)phone {
    self.codeButton.verifyCodeStatus = GSCommonLoginVerificationCodeStatusSending;
    BCPhoneCaptchaRequest *requst = [BCPhoneCaptchaRequest new];
    requst.phone = phone;
    //
    WEAK_SELF
    [requst didRequestCompleted:^{
        
    }];
    [requst didRequestSuccessed:^(id result, id page) {
        wself.codeButton.verifyCodeStatus = GSCommonLoginVerificationCodeStatusWaiting;
        BCPhoneCaptchaResponse *resp = result;
        if (resp.msg&&wself.view) {
            [QMUITips showInfo:resp.msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:resp.msg]];
        }
    }];
    [requst didRequestFailed:^(NSError *error) {
        wself.codeButton.verifyCodeStatus = GSCommonLoginVerificationCodeStatusReSend;
        if (error&&wself.view) {
            NSString *msg = error.domain;
            [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }];
    [requst requestServer];
}
//发送邮箱验证码
- (void)requestEmailCaptchaAddress:(NSString *)email {
    self.codeButton.verifyCodeStatus = GSCommonLoginVerificationCodeStatusSending;
    BCEmailCaptchaRequest *request = [BCEmailCaptchaRequest new];
    request.email = email;
    WEAK_SELF
    [request didRequestCompleted:^{
        
    }];
    [request didRequestSuccessed:^(id result, id page) {
        wself.codeButton.verifyCodeStatus = GSCommonLoginVerificationCodeStatusWaiting;
        //
        BCEmailCaptchaResponse *resp = result;
        if (resp.msg&&wself.view) {
            [QMUITips showInfo:resp.msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:resp.msg]];
        }
    }];
    [request didRequestFailed:^(NSError *error) {
        wself.codeButton.verifyCodeStatus = GSCommonLoginVerificationCodeStatusReSend;
        if (error&&wself.view) {
            NSString *msg = error.domain;
            [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }];
    [request requestServer];
}



#pragma mark -
- (void)nextStepButtonDidClickedAction {
    [self.view endEditing:true];
    //更新数据
    [GSCommonLoginDataManager sharedData].registerModel.verifyCode = self.verifyCodeView.verifyCode;
    //
    [self requestRegisterAction];
}


#pragma mark -
- (void)requestRegisterAction {
    NSString *account = [GSCommonLoginDataManager sharedData].registerModel.username;
    GSCCommonLoginAccountType type = [NSString gscLoginAccountTypeWithString:account];
    if (type==GSCCommonLoginAccountTypePhone) {
        [self requestPhoneRegisterAction:account];
    }else {
        [self requestEmailRegisterAction:account];
    }
}
//手机号码注册
- (void)requestPhoneRegisterAction:(NSString *)phone {
    [self.view showLoginToast];
    BCPhoneRegisterRequest *request = [BCPhoneRegisterRequest new];
    request.phone = phone;
    request.captcha = self.verifyCodeView.verifyCode;
    request.password = [GSCommonLoginDataManager sharedData].registerModel.password;
    request.uuid = [GeneralParameterManager sharedGeneral].uuid;
    //
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.view hideLoginToast];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCPhoneRegisterResponse *resp = result;
        if (resp.data) {
            [[BCUserManager sharedUser] userLoginSuccessUpdateUserLoginData:resp.data];
        }
        [wself registerSuccessToHomeAction];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *msg = error.domain;
            [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }];
    [request requestServer];
    
}
//邮箱注册
- (void)requestEmailRegisterAction:(NSString *)email {
    [self.view showLoginToast];
    BCEmailRegisterRequest *request = [BCEmailRegisterRequest new];
    request.email = email;
    request.captcha = self.verifyCodeView.verifyCode;
    request.password = [GSCommonLoginDataManager sharedData].registerModel.password;
    request.uuid = [GeneralParameterManager sharedGeneral].uuid;
    //
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.view hideLoginToast];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCEmailRegisterResponse *resp = result;
        if (resp.data) {
            [[BCUserManager sharedUser] userLoginSuccessUpdateUserLoginData:resp.data];
        }
        [wself registerSuccessToHomeAction];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error) {
            NSString *msg = error.domain;
            [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }];
    [request requestServer];
}



#pragma mark - 注册成功返回首页
- (void)registerSuccessToHomeAction {
    __weak typeof(self) wself = self;
    [GSCommonLoginSuccessController showFromController:self succssType:GSCommonLoginSuccessTypeRegisterSuccuss complete:^{
        [wself.navigationController dismissViewControllerAnimated:true completion:^{
            [wself.navigationController popToRootViewControllerAnimated:true];
            [[NSNotificationCenter defaultCenter] postNotificationName:UserCommonLoginSuccessNotification object:nil];
        }];
        //触发绑定邀请码
        [[GSCommonLoginDataManager sharedData] userRegisterSuccessBindInvatationCode];
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:true];
}

@end
